package com.atguigu.orderservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.orderservice.entity.TOrder;
import com.atguigu.orderservice.service.TOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author ms
 * @since 2022-05-30
 */
@RestController
@RequestMapping("/orderservice/order")
public class TOrderController {


    @Autowired
    private TOrderService orderService;

    @ApiOperation("创建订单")
    @PostMapping("create/{courseId}")
    public R create(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        //创建订单，返回订单号
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //String memberId = "1530859100433301505";
        if (StringUtils.isEmpty(memberId)) {
            return R.error().message("请登录");
        }
        String orderNo = orderService.createOrder(courseId, memberId);
        return R.ok().data("orderNo", orderNo);
    }

    @ApiOperation("获取订单信息")
    @GetMapping("get/{orderNoId}")
    public R get(@PathVariable("orderNoId") String orderNoId) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNoId);
        TOrder order = orderService.getOne(wrapper);
        return R.ok().data("order", order);
    }

    @ApiOperation("查询用户是否买了该课程")
    @GetMapping("getOrderStatus/{courseId}")
    public R getOrderStatus(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) {
            return R.ok().data("status", false);
        }
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId).eq("member_id", memberId).select("status");
        TOrder order = orderService.getOne(wrapper);
        if (order == null) {
            return R.ok().data("status", false);
        }
        if (order.getStatus() == 0) {
            return R.ok().data("status", false);
        }
        return R.ok().data("status", true);
    }

}

